﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.ReturnMonerys;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Runtime.InteropServices;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.ReturnMonerys
{
    public class AddReturnMoneryCommandHandler : IRequestHandler<AddReturnMoneryCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<ReturnMoney> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;

        public AddReturnMoneryCommandHandler(SqlsugarDb<ReturnMoney> db, IHttpContextAccessor httpContextAccessor, IMapper mapper)
        {
            this.db = db;

            this.httpContextAccessor = httpContextAccessor;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddReturnMoneryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                var addentity = mapper.Map<ReturnMoney>(request);
                addentity.CreateName = httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.Name)?.Value;
                addentity.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                addentity.CreateTime = DateTime.Now;
                addentity.RefundProgess = 1;//未退款；
                if (string.IsNullOrEmpty(addentity.SalesRefundNo))
                {
                    result.message = "编号不能为空";
                    result.Code = Enumcode.Nonull;
                    result.data = 0;
                    return result;
                }
                if (addentity.CustomerId > 0)
                {
                    //退货类型为销售
                    addentity.Refundstyle = 1;
                }
                if (addentity.SupplieId > 0)
                {
                    addentity.Refundstyle = 2;
                }
                var returnrow = await db.AddAsync(addentity);
                if (returnrow > 0)
                {
                    result.Code = Enumcode.ok;
                    result.message = "退款信息添加成功";
                    result.data = 1;
                }
                else
                {
                    result.Code = Enumcode.fail;
                    result.message = "退款信息添加失败";
                    result.data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = Enumcode.fail;
                result.message =ex.Message;
                result.data = 0;
                throw;
            }
            return await Task.FromResult(result);


        }
    }
}
